#include "map.h"

namespace map_ns{
    #define down 1
    #define right 2
    #define left 4
    #define up 8
    #define WALL -1
    #define NOTHING 0
    struct block {
        int row, column, direction;
        block(int _row, int _column, int _direction) {
            row = _row;
            column = _column;
            direction = _direction;
	    }
    };
    Point start, end;
    int x_num = 1, y_num = 1; //startpoint
    int G[1000][1000];
    int _row, _col;
};

using namespace map_ns;

std::vector<block> myblock;


void FindBlock() {
	if (x_num + 1 <= _row && G[x_num + 1][y_num] == WALL) { //down
		myblock.push_back(block(x_num + 1, y_num, down));
	}
	if (y_num + 1 <= _col && G[x_num][y_num + 1] == WALL) { //right
		myblock.push_back(block(x_num, y_num + 1, right));
	}
	if (x_num - 1 >= 1 && G[x_num - 1][y_num] == WALL) { //up
		myblock.push_back(block(x_num - 1, y_num, up));
	}
	if (y_num - 1 >= 1 && G[x_num][y_num - 1] == WALL) { //left
		myblock.push_back(block(x_num, y_num - 1, left));
	}
}

void start_mapping() {
    
	memset(G, WALL, sizeof(G));
	G[1][1] = NOTHING;
	start.x = start.y = 1;
    _row= row-2;
    _col= col-2;

	srand((unsigned)time(NULL));
	FindBlock();
	while (myblock.size()) {
		int BlockSize = myblock.size();
		int randnum = rand() % BlockSize;
		block SelectBlock = myblock[randnum];
		x_num = SelectBlock.row;
		y_num = SelectBlock.column;
		switch (SelectBlock.direction) {
			case down: {
				x_num++;
				break;
			}
			case right: {
				y_num++;
				break;
			}
			case left: {
				y_num--;
				break;
			}
			case up: {
				x_num--;
				break;
			}
		}
		if (G[x_num][y_num] == WALL) {
			G[SelectBlock.row][SelectBlock.column] = G[x_num][y_num] = NOTHING;
			FindBlock();
		} 
		myblock.erase(myblock.begin() + randnum);
	}

	for (int i = 0; i <= _row + 1; i++) {
		for (int j = 0; j <= _col + 1; j++) {
			if (G[i][j] == -1)
				G[i][j] = 1;
		}
	}


    for (int i = 0; i <= _row + 1; i++) {
		for (int j = 0; j <= _col + 1; j++) {
			
			map[i][j] = G[i][j] ;
		}
	}
}
